package org.example.linkedList;

/**
 * @Auther: wangbw
 * @Date:2020/12/2
 * @Description: org.example.linkedList
 * @version: 1.0
 */
public class LinkLoop3 {
    public static void main(String[] args) {
        Node head = Node.createNode(8);
        Node cur = head;
        while (cur != null && cur.next != null){
            cur = cur.next;
        }
        cur.setNext(head.next.next);
        //0-1-2-3-4-5-6-7-8-2
        System.out.println(isCycle(head));
        Node node = enterNode(head);
        System.out.println(node.getData());
    }

    private static Node enterNode(Node head) {
        //x+a=s;2s=x+a+nr;s=nr;x=nr-a;
        Node fast = head;
        Node slow = head;
        Boolean isMeet=false;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow){
                isMeet = true;
                break;
            }
        }
        if (!isMeet)
            return null;
        slow = head;
        while(slow != null){
            if (slow == fast){
                return slow;
            }
            slow = slow.next;
            fast = fast.next;
        }
        return null;
    }

    private static boolean isCycle(Node head) {
        if (head == null || head.next == null){
            return false;
        }
        Node fast = head.next.next;
        Node slow = head.next;
        while(fast != null && fast.next != null){
            if (fast == slow){
                return true;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        return false;
    }
}
